package hk.m4s.lr.repair.test.utils;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import hk.m4s.lr.repair.test.R;

public class ToastUtil {
	private static PopupWindow popupWindow;

	public static void toast(Context context, String msg) {
		// Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
		if(context==null){
			return;
		}
		View contentView = LayoutInflater.from(context).inflate(
				R.layout.toast_dialog_view, null);
		pop(msg, contentView);
		handler.postDelayed(runnable, 1500);// 打开定时器，执行操作
	}
	public static void toastmg(Context context, String msg) {
		// Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
		if(context==null){
			return;
		}
		View contentView = LayoutInflater.from(context).inflate(
				R.layout.toast_dialog_views, null);
		pop(msg, contentView);
		handler.postDelayed(runnable, 1500);// 打开定时器，执行操作
	}
	public static void toast(Context context, int msgId) {
		if(context==null){
			return;
		}
		View contentView = LayoutInflater.from(context).inflate(
				R.layout.toast_dialog_view, null);
		pop(context.getResources().getString(msgId), contentView);
		handler.postDelayed(runnable, 1500);
	}

	public static void toastLong(Context context, int msgId) {
		if(context==null){
			return;
		}
		View contentView = LayoutInflater.from(context).inflate(
				R.layout.toast_dialog_view, null);
		pop(context.getResources().getString(msgId), contentView);
		handler.postDelayed(runnable, 3000);
	}

	private static void pop(String msg, View contentView) {
		try{
		contentView.getBackground().setAlpha(95);
		if(popupWindow!=null){
			if (popupWindow.isShowing()) {
				popupWindow.dismiss();
			}
		}
		popupWindow = new PopupWindow(contentView,
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		TextView mono_dialog_text = (TextView) contentView
				.findViewById(R.id.toast_dialog_text);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		mono_dialog_text.setText(msg);
		popupWindow.showAtLocation(contentView, Gravity.BOTTOM
				| Gravity.CENTER_HORIZONTAL, 0, 400);
		contentView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(popupWindow!=null){
					if (popupWindow.isShowing()) {	
						popupWindow.dismiss();
					}
				}	
			}
		});
		}catch(Exception e){
		}
	}
	final static Handler handler = new Handler();
	static Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			// 在此处添加执行的代码
			try{
			if (popupWindow.isShowing()) {
				popupWindow.dismiss();
			}
			}catch(Exception e){}
			handler.removeCallbacks(this);
		}

	};

}
